﻿#region description
/*
 * ViesGr library - Copyright (C) 2011 Petros Kyladitis
 * A greek VIES VAT number validation library,
 * developed in SharpDevelop, at C# language, targeted .NET/Mono
 * 
 * The library's methods check if a VIES VAT number is valid, and
 * NOT if exists and corresponds to a natural person or a legal entity.
 * 
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */
 #endregion
 
using System;
using System.Collections.Generic;

namespace Multipetros{
	
	/// <summary>
	/// The class method check if a VIES VAT number is valid
	/// </summary>
	public static class ViesGr{
		
		/// <summary>
		/// Static method for VIES VAT ID validation checking
		/// </summary>
		/// <param name="viesVatId">The VIES VAT ID to check</param>
		/// <returns>true if the VIES VAT ID is valid, false if it's invalid</returns>
		public static bool IsValid(int viesVatId){
			
			// all GR VIES IDs has 9 digits and starts counting from 100000000
			if(viesVatId > 999999999 || viesVatId < 9999999) 
				return false ; 
			
			//deploy the 9 digits of the number to a table,
			//beginning from LSD at last table position [8] => to MSD at first table position [0]
			int digit ;
			byte[] digiTable = new byte[9] ;	
			for(int i=digiTable.Length-1; i>=0; i--){
				digit = viesVatId%10;
				viesVatId = (viesVatId-digit)/10;
				digiTable[i]=(byte)digit;
			}
			
			//multiply all nums in table[0 to 7] by 2^(8-n) [n = table position]
			//and summarize the products
			int multiplier = 256;
			int sum = 0;			
			for(int i=0; i<digiTable.Length-1; i++){
				sum+=digiTable[i]*multiplier;
				multiplier/=2;
			}
			
			//if the modulus of the sumarized products by 11 (a num from 0 to 10; if 10 set it to 0) 
			//equals the last digit of the id (table last position [8]), the id is valid
			sum%=11;
			if(sum==10) sum=0;			
			if(sum!=digiTable[8])
				return false;
			return true;
		}
	}
}